package com.c5p1ng.route.util;

import javax.servlet.http.HttpServletRequest;


public class IPUtil {

    /**
     * 获取客户端访问真实地址
     */
    public static String getClientAddress (HttpServletRequest request) {
        String ip = request.getHeader(X_Real_IP);

        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader(X_FORWARDED_FOR);
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader(WL_PROXY_CLIENT_IP);
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader(HTTP_CLIENT_IP);
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader(HTTP_X_FORWARDED_FOR);
        }
        if (ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        //取本机IP
        if (LOCALHOST_1.equals(ip) || LOCALHOST_2.equals(ip)) {
            ip = LocalIpUtil.getLocalIp();
        }
        return ip;
    }

    private static final String LOCALHOST_1 = "127.0.0.1";

    private static final String LOCALHOST_2 = "0:0:0:0:0:0:0:1";

    private static final String X_Real_IP = "X-Real-IP";

    private static final String X_FORWARDED_FOR = "X-Forwarded-For";

    private static final String WL_PROXY_CLIENT_IP = "WL-Proxy-Client-IP";

    private static final String HTTP_CLIENT_IP = "HTTP_CLIENT_IP";

    private static final String HTTP_X_FORWARDED_FOR = "HTTP_X_FORWARDED_FOR";

    private static final String UNKNOWN = "unknown";

}
